package com.wjy.icu.common.impl;



import com.wjy.icu.common.CacheManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @author: wangjunyong
 * @date: 2019/4/24 14:35
 */
@Component
public class RedisCaheManage implements CacheManage {

    //    @Autowired
//    StringRedisTemplate redisTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }


    @Override
    public <T> void set(String key, T value) {

        redisTemplate.opsForValue().set(key, value);
    }

    @Override
    public <T> void set(String key, T value, Long timeSpan) {
        redisTemplate.opsForValue().set(key, value, timeSpan, TimeUnit.MILLISECONDS);
    }

    @Override
    public <T> T get(String key) {
        ValueOperations<String, T> operations = redisTemplate.opsForValue();
        return operations.get(key);
    }

    @Override
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public boolean isExist(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public void expire(String key, Long timeSpan) {
        redisTemplate.expire(key, timeSpan, TimeUnit.MILLISECONDS);
    }

    @Override
    public <T> void addSet(String key, T value) {
        redisTemplate.opsForSet().add(key, value);
    }

    @Override
    public Set<?> getList(String key) {

        return redisTemplate.opsForSet().members(key);
    }

    @Override
    public <T> void removeSet(String key, T value) {
        redisTemplate.opsForSet().remove(key, value);
    }

    @Override
    public <T> void removeAll() {
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
    }
}
